import {form} from "../config/index.js";

export default {
    template: `
         <el-dialog
            v-model="visible"
            :title="title"
            width="50%"
          >
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
                <el-form-item label="gpt地址" prop="path">
                    <el-input clearable v-model="path" />
                </el-form-item>
                <el-form-item label="预置指令" prop="order">
                    <el-input clearable v-model="order" />
                </el-form-item>
                <el-form-item label="字段规则" prop="rule1">
                    <el-input clearable v-model="rule1" />
                </el-form-item>
                <el-form-item label="类型规则" prop="rule2">
                    <el-input clearable v-model="rule2" />
                </el-form-item>
                <el-form-item label="api-key" prop="pass">
                    <el-input clearable v-model="pass" />
                </el-form-item>
                <el-form-item label="对话" prop="conversation">
                    <el-input clearable v-model="conversation" @keydown.enter="operation.sendMsg" />
                </el-form-item>
                <el-form-item label="sql" prop="sql">
                    <el-input :rows="16" resize="none" type="textarea" clearable v-model="formData.sql" />
                </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="visible=false">取消</el-button>
                <el-button type="primary" @click="operation.save">保存</el-button>
              </span>
            </template>
        </el-dialog>
    `,
    setup(props, context) {
        const formRef = Vue.ref(null);
        const visible = Vue.ref(false)
        const title = Vue.ref("")
        const operation = {
            save: async () => {
                (await getRef(formRef)).validate(async (valid) => {
                    if (valid) {
                        context.emit("save", form.formData)
                    }
                })
            },
            sendMsg: async () => {
                form.formData.sql = ''
                fetch(path.value, {
                    method: 'POST',
                    body: JSON.stringify({
                        "messages": [
                            {
                                "role": "system",
                                "content": order.value
                            },
                            {
                                "role": "system",
                                "content": rule1.value
                            },
                            {
                                "role": "system",
                                "content": rule2.value
                            },
                            ...que,
                            {
                                "role": "user",
                                "content": conversation.value
                            }
                        ],
                        "max_tokens": 2000,
                        "stream": true,
                        "model": "gpt-3.5-turbo",
                        "temperature": 1,
                        "presence_penalty": 1
                    }),
                    // headers: {Authorization: `Bearer nk-${pass.value}`},
                    headers: {
                        Authorization: `Bearer ${pass.value}`,
                        "Content-Type": "application/json",
                    },
                })
                    .then(response => {
                        const reader = response.body.getReader();
                        return new ReadableStream({
                            start(controller) {
                                function push() {
                                    reader.read().then(({done, value}) => {
                                        if (done) {
                                            controller.close();
                                            return;
                                        }
                                        controller.enqueue(value);
                                        push();
                                    });
                                }

                                push();
                            },
                        });
                    })
                    .then(stream => new Response(stream))
                    .then(response => {
                        let endStr = '';
                        const reader = response.body.getReader();

                        function read() {
                            reader.read().then(({done, value}) => {
                                if (done) {
                                    return;
                                }
                                const text = endStr + new TextDecoder('utf-8').decode(value);
                                //使用data:分割
                                text.split('data:').filter(e => e).forEach((item, index) => {
                                    if (item.endsWith('[DONE]\n\n')) return
                                    try {
                                        let data = JSON.parse(item)
                                        let sql = data?.choices[0]?.delta?.content
                                        form.formData.sql += sql ?? ''
                                    } catch (e) {
                                        endStr = item
                                    }
                                })
                                read();
                            });
                        }

                        read();
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            }
        }
        const path = Vue.ref('https://api.xiaoai.plus/v1/chat/completions')
        const order = Vue.ref("你是sql小能手,不管问你什么你只需要回答能直接执行的mysql建表sql不带格式的纯文本即可,不要使用MD语法,不要添加任何说明,用户会提供字段功能和表功能,索引(非必须),唯一索引(禁止),编码(utf8mb4_general_ci),引擎(InnoDB),字段要严格遵守驼峰命名,sql中表和字段都要加中文功能注释,注意字段名和表名是英文,必须判断表不存在才创建")
        const rule1 = Vue.ref("默认包含字段id(bigint类型自增主键),create_time(bigint类型),create_user_id(bigint类型),update_time(bigint类型),update_user_id(bigint类型)")
        const rule2 = Vue.ref("表字段只能使用varchar,longtext,json,bit,int,tinyint,bigint,decimal其他类型不可使用,如非指定,不要加非空,小数类型必须为decimal")
        const conversation = Vue.ref("抖音用户表  字段：姓名 年龄(加索引) 性别 手机号 微信号 住址 邮箱")
        const pass = Vue.ref("sk-ZhILZrHdEF8AVMekEc19E74298Cb4d46B8220b93Ea94356c")
        let que = []
        Vue.watch(visible, async val => val || (await getRef(formRef)).resetFields())
        return Object.assign({
            visible,
            title,
            path,
            order,
            rule1,
            rule2,
            pass,
            conversation,
            formRef,
            operation,
        }, form)
    }
}